/**
 * 匿名用户信息表单组件
 * 用于收集匿名用户的名称、邮箱和个人网址
 */

import React, { useState, useEffect } from 'react';
import { Input, Button, message, Form, notification } from 'antd';
import { UserOutlined, MailOutlined, LinkOutlined, UpOutlined, DownOutlined, CheckCircleOutlined } from '@ant-design/icons';
import { updateAnonymousUserInfo } from '@/services/AnonymousUser/api';
import styles from './index.less';

interface AnonymousUserInfoFormProps {
  userId: string | number;
  initialName?: string;
  initialEmail?: string;
  initialLink?: string;
  onSubmitSuccess?: () => void;
}

const AnonymousUserInfoForm: React.FC<AnonymousUserInfoFormProps> = ({
  userId,
  initialName = '',
  initialEmail = '',
  initialLink = '',
  onSubmitSuccess,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [isCollapsed, setIsCollapsed] = useState(false);
  const [lastScrollY, setLastScrollY] = useState(0);
  const [api, contextHolder] = notification.useNotification();
  const [isHiding, setIsHiding] = useState(false);

  // 监听滚动事件，自动收缩表单
  useEffect(() => {
    const handleScroll = () => {
      const currentScrollY = window.scrollY;
      
      // 当向下滚动超过50px时，自动收缩
      if (currentScrollY > 50 && currentScrollY > lastScrollY && !isCollapsed) {
        setIsCollapsed(true);
      }
      
      setLastScrollY(currentScrollY);
    };

    window.addEventListener('scroll', handleScroll, { passive: true });
    return () => window.removeEventListener('scroll', handleScroll);
  }, [lastScrollY, isCollapsed]);

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      const result = await updateAnonymousUserInfo({
        userId,
        name: values.name,
        email: values.email,
        link: values.link,
      });

      if (result.data.success) {
        // 保存到浏览器localStorage
        localStorage.setItem('anonymousUserName', values.name);
        localStorage.setItem('anonymousUserEmail', values.email);
        if (values.link) {
          localStorage.setItem('anonymousUserLink', values.link);
        }

        // 先触发消失动画
        setIsHiding(true);

        // 获取当前时间段的问候语
        const getGreeting = () => {
          const hour = new Date().getHours();
          if (hour < 12) return '早上好';
          if (hour < 18) return '中午好';
          return '晚上好';
        };

        // 显示美化的通知
        const key = `open${Date.now()}`;
        const btn = (
          <Button 
            type="primary" 
            size="small" 
            onClick={() => api.destroy(key)}
            style={{
              background: '#0891b2',
              borderRadius: '6px',
              fontWeight: 500
            }}
          >
            确认
          </Button>
        );

        api.success({
          message: (
            <div style={{ fontWeight: 600, color: '#262626', fontSize: '16px' }}>
              🎉 {getGreeting()}，{values.name}
            </div>
          ),
          description: (
            <div style={{ color: '#595959', lineHeight: '1.8' }}>
              <div style={{ marginBottom: '8px' }}>
                <span style={{ fontWeight: 600, color: '#262626' }}>您的邮箱为：</span>
                <span style={{ color: '#595959' }}>{values.email}</span>
              </div>
              {values.link && values.link.trim() && (
                <div style={{ marginBottom: '8px' }}>
                  <span style={{ fontWeight: 600, color: '#262626' }}>个人网址为：</span>
                  <span style={{ color: '#595959' }}>{values.link}</span>
                </div>
              )}
              <div style={{ 
                marginTop: '12px', 
                paddingTop: '12px', 
                borderTop: '1px solid #e5e7eb',
                fontSize: '13px',
                color: '#8c8c8c',
                fontWeight: 500
              }}>
                💡 后续可以在 
                <span style={{ fontWeight: 600, color: '#0891b2', margin: '0 4px' }}>游客模式</span> 
                按钮中修改喔
              </div>
            </div>
          ),
          btn,
          key,
          duration: 0,
          placement: 'topRight',
          style: {
            width: 400,
            background: '#ffffff',
            border: '1px solid #e5e7eb',
            boxShadow: '0 8px 24px rgba(0, 0, 0, 0.08), 0 2px 8px rgba(0, 0, 0, 0.04)',
            borderRadius: '16px',
          },
          icon: <CheckCircleOutlined style={{ color: '#0891b2', fontSize: '28px' }} />,
        });

        // 等待动画完成后再调用回调
        setTimeout(() => {
          onSubmitSuccess?.();
        }, 800);
      } else {
        message.error(result.data.message || '保存失败，请重试');
      }
    } catch (error) {
      if (error instanceof Error && 'errorFields' in error) {
        // 表单验证失败
        message.warning('请填写必填信息');
      } else {
        message.error('保存失败，请重试');
      }
    } finally {
      setLoading(false);
    }
  };

  const toggleCollapse = () => {
    setIsCollapsed(!isCollapsed);
  };

  return (
    <>
      {contextHolder}
      <div className={`${styles.formContainer} ${isCollapsed ? styles.collapsed : ''} ${isHiding ? styles.hiding : ''}`}>
      {isCollapsed ? (
        // 收缩状态：显示简化信息
        <div className={styles.collapsedView} onClick={toggleCollapse}>
          <div className={styles.collapsedContent}>
            <div className={styles.collapsedItem}>
              <span className={styles.label}>名称</span>
              <span className={styles.value}>{form.getFieldValue('name') || '未填写'}</span>
            </div>
            <div className={styles.collapsedDivider}>|</div>
            <div className={styles.collapsedItem}>
              <span className={styles.label}>邮箱</span>
              <span className={styles.value}>{form.getFieldValue('email') || '未填写'}</span>
            </div>
            <div className={styles.collapsedDivider}>|</div>
            <div className={styles.collapsedItem}>
              <span className={styles.label}>网址</span>
              <span className={styles.value}>{form.getFieldValue('link') || '未填写'}</span>
            </div>
          </div>
          <DownOutlined className={styles.collapseIcon} />
        </div>
      ) : (
        // 展开状态：显示完整表单
        <>
          <div className={styles.formHeader}>
            <div className={styles.formTip}>
              <span>👋 欢迎！请填写您的邮箱以发布说说和评论</span>
            </div>
            <UpOutlined className={styles.collapseIcon} onClick={toggleCollapse} />
          </div>
          <Form
            form={form}
            layout="inline"
            className={styles.infoForm}
            initialValues={{
              name: initialName,
              email: initialEmail,
              link: initialLink,
            }}
          >
            <Form.Item
              name="name"
              rules={[{ required: true, message: '请输入昵称' }]}
              className={styles.formItem}
            >
              <Input
                prefix={<UserOutlined />}
                placeholder="昵称"
                maxLength={20}
                className={styles.input}
              />
            </Form.Item>
            <Form.Item
              name="email"
              rules={[
                { required: true, message: '请输入邮箱' },
                { type: 'email', message: '请输入有效的邮箱地址' },
              ]}
              className={styles.formItem}
            >
              <Input
                prefix={<MailOutlined />}
                placeholder="邮箱"
                maxLength={50}
                className={styles.input}
              />
            </Form.Item>
            <Form.Item
              name="link"
              rules={[
                { type: 'url', message: '请输入有效的网址' },
              ]}
              className={styles.formItem}
            >
              <Input
                prefix={<LinkOutlined />}
                placeholder="个人网址（选填）"
                maxLength={100}
                className={styles.input}
              />
            </Form.Item>
            <Form.Item className={styles.formItem}>
              <Button
                type="primary"
                onClick={handleSubmit}
                loading={loading}
                className={styles.submitBtn}
              >
                确认
              </Button>
            </Form.Item>
          </Form>
        </>
      )}
      </div>
    </>
  );
};

export default AnonymousUserInfoForm;

